/*
* Copyright© 2018 Shanxi Lu'an Taihang Laihui Net Tech co.,LTD.
*/
package com.laihuichuxing.netty.server.server;

import com.laihuichuxing.netty.common.constant.NettyConstant;
import com.laihuichuxing.netty.common.core.codc.RequestDecoder;
import com.laihuichuxing.netty.common.core.codc.ResponseEncoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;

/**
 * Description: netty服务端
 *
 * @author YangGuang
 * @since: 1.0
 * Create Date Time: 2018/7/4 17:33
 * Update Date Time:
 * @see
 */
@Component
public class Server implements ApplicationRunner {

    @Autowired
    private NettyConstant nettyConstant;

    private static Logger log = LoggerFactory.getLogger(Server.class);

    public void start() {
        // 服务类
        ServerBootstrap b = new ServerBootstrap();
        // 创建boss和worker
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup(4);
        try {
            // 设置
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new IdleStateHandler(nettyConstant.getReadTime(), nettyConstant.getWriteTime(), nettyConstant.getReadAndWriteTime()));
                            ch.pipeline().addLast(new RequestDecoder());
                            ch.pipeline().addLast(new ResponseEncoder());
                            ch.pipeline().addLast(new ServerHandler());
                        }
                    })
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .option(ChannelOption.SO_REUSEADDR, true)
                    .option(ChannelOption.AUTO_READ, true)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childOption(ChannelOption.SO_REUSEADDR, true)
                    .childOption(ChannelOption.AUTO_READ, true)
                    .bind(new InetSocketAddress(nettyConstant.getPort())).sync();
            if (log.isInfoEnabled()) {
                log.info("长连接开启成功");
            }
        } catch (Exception e) {
            if (log.isErrorEnabled()) {
                log.error("长连接开启失败,失败原因:{}", e);
            }
        }
    }

    @Override
    public void run(ApplicationArguments applicationArguments) throws Exception {
        if (log.isInfoEnabled()) {
            log.info("长连接开启");
        }
        start();
    }

}
